package com.icoolkj.learn.juc.future;

import com.icoolkj.learn.juc.base.utils.SleepTools;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/03/05 14:26
 */
@Slf4j
public class CFDemo2 {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            SleepTools.second(1);
            if (new Random().nextInt(10) % 2 == 0) {
                int i = 12 / 0; // 抛出异常
            }
            log.info("执行结束！");
            return "test";
        });

        future.whenComplete(new BiConsumer<String, Throwable>() {
            @Override
            public void accept(String s, Throwable throwable) {
                log.info("{} 执行完成！", s); // 就算是抛出异常也会执行
            }
        });

        future.exceptionally(new Function<Throwable, String>() {
            @Override
            public String apply(Throwable throwable) {
                log.info("执行失败：{}", throwable.getMessage());
                return "异常...";
            }
        });

        future.join();


    }
}
